const VideoReview = require('./../models/videoReviewModel');
const Video = require('./../models/videoModel');
const catchAsync = require('./../utils/catchAsync.js');
const AppError = require('./../utils/appError.js');
const APIFeatures = require('./../utils/apiFeatures.js');
const factory = require('./handlerFactory');
exports.setvideoReviewUserId = (req, res, next) => {
  // Allow nested routes
  // if (!req.body.tour) req.body.tour = req.params.tourId;
  if (!req.body.user) req.body.user = req.user.id;
  next();
};

// 创建 视频评论 的函数（在用户的）
exports.createVideoReview = catchAsync(async (req, res, next) => {
  const { user, video, review, rating } = req.body;
  const video1 = await Video.findById(video);
  // 创建收藏夹
  const videoReview = await VideoReview.create({
    review: review,
    rating: rating,
    video: video,
    user: user,
  });

  if (!video1) {
    return next(new AppError('video not found', 404));
  }
  if (!video1.videoReviews || !Array.isArray(video1.videoReviews)) {
    video1.videoReviews = []; // 如果不存在或者不是数组，可以进行初始化
  }
  // 将视频评论添加到视频中
  if (!video1.videoReviews.includes(videoReview._id)) {
    video1.videoReviews.push(videoReview._id);
    await video1.save();
  }
  // 将videoReview添加到当前video的评论 列表中
  // 假设你的用户模型是 User，可以通过 userId 找到当前用户
  // await userU.save();
  res.status(200).json({
    status: 'success',
    videoReview,
    message: 'videoReview added to video successfully',
  });
});
exports.getAllvideoReviews = catchAsync(async (req, res, next) => {
  const { user, video } = req.body;
  const video1 = await Video.findById(video);
  if (!video1) {
    return next(new AppError('video not found', 404));
  }

  res.status(200).json({
    status: 'success',
    videoReviewList: video1.videoReviews,
    message: 'videoReviewList is above',
  });
});

// exports.getAllvideoReviews = factory.getAll(VideoReview);

exports.getvideoReview = factory.getOne(VideoReview);
// exports.createvideoReview = factory.createOne(VideoReview);
exports.updatevideoReview = factory.updateOne(VideoReview);
exports.deletevideoReview = factory.deleteOne(VideoReview);
